
// 获取分类
async function getCategoryRequest() {
    const res = await $.ajax({
        url: 'http://localhost:8081/api/getCategory.php',
        type: 'get'
    })
    return res
}

// 创建分类 Fragment
function createCategoryFragment(categoryData) {
    const fragment = document.createDocumentFragment()
    categoryData.data.forEach(item => {
        const option = document.createElement('option')
        option.value = item.id
        option.innerHTML = item.name
        fragment.append(option)
    })
    return fragment
}

// 设置分类
async function setCategory() {
    const selectArticle = document.querySelector('.category .select')
    const selectHeader = document.querySelector('.header .search .select')
    const categoryData = await getCategoryRequest()
    if (categoryData.code === 1) {
        selectArticle.appendChild(createCategoryFragment(categoryData))
        selectHeader.appendChild(createCategoryFragment(categoryData))
    }
}
setCategory()

// 获取文章详情
async function getArticleDetailsRequest() {
    const articleId = new URL(location.href).searchParams.get('id')
    const res = await $.ajax({
        url: 'http://localhost:8081/api/getArticleDetails.php/' + articleId,
        type: 'get'
    })
    return res
}

// 渲染文章详情
async function renderArticleDetails() {
    const articleData = await getArticleDetailsRequest()
    console.log(articleData)
    document.querySelector('.form .form-item input').value = articleData.data.title
    document.querySelector('.form .form-item select').value = articleData.data.category_id
    document.querySelector('.form .form-item textarea').innerHTML = articleData.data.content
}
renderArticleDetails()

// 编辑文章
$('.form .btn').click(function () {
    const article_id = new URL(location.href).searchParams.get('id')
    const title = document.querySelector('.form .title input').value
    const category_id = document.querySelector('.form .category select').value
    const content = document.querySelector('.form .content textarea').value

    editArticleRequest({
        article_id,
        title,
        category_id,
        content
    })
})

// 更新文章请求
async function editArticleRequest(data) {
    const res = await $.ajax({
        url: 'http://localhost:8081/api/articleEdit.php',
        type: 'put',
        data: data
    })
    if (res.code === 1) {
        myAlert(true, '更新成功')
    } else {
        myAlert(false, res.msg)
    }
}